﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DbContextInitializer.cs" company="">
//   
// </copyright>
// <summary>
//   The db context initializer.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

#region

using System;

#endregion

namespace Common.Data
{
    /// <summary>
    /// The db context initializer.
    /// </summary>
    public class DbContextInitializer
    {
        /// <summary>
        /// The _sync lock.
        /// </summary>
        private static readonly object _syncLock = new object();

        /// <summary>
        /// The _instance.
        /// </summary>
        private static DbContextInitializer _instance;

        /// <summary>
        /// The _is initialized.
        /// </summary>
        private bool _isInitialized;

        /// <summary>
        /// Initializes a new instance of the <see cref="DbContextInitializer"/> class.
        /// </summary>
        protected DbContextInitializer()
        {
        }

        /// <summary>
        /// The instance.
        /// </summary>
        /// <returns>
        /// The <see cref="DbContextInitializer"/>.
        /// </returns>
        public static DbContextInitializer Instance()
        {
            if (_instance == null)
            {
                lock (_syncLock)
                {
                    if (_instance == null)
                    {
                        _instance = new DbContextInitializer();
                    }
                }
            }

            return _instance;
        }

        /// <summary>
        /// This is the method which should be given the call to intialize the DbContext; e.g.,
        ///     DbContextInitializer.Instance().InitializeDbContextOnce(() =&gt; InitializeDbContext());
        ///     where InitializeDbContext() is a method which calls DbContextManager.Init()
        /// </summary>
        /// <param name="initMethod">
        /// </param>
        public void InitializeDbContextOnce(Action initMethod)
        {
            lock (_syncLock)
            {
                if (!_isInitialized)
                {
                    initMethod();
                    _isInitialized = true;
                }
            }
        }
    }
}